#include <QDomDocument>
#include <QFile>
#include <QTextStream>

#include "Templater.h"

Templater::Templater(QObject *parent) :
    QObject(parent)
{
}

QString Templater::fileName() const
{
    return m_fileName;
}

void Templater::setFileName(const QString &fileName)
{
    m_fileName = fileName;
}

QString Templater::filter() const
{
    return m_filter;
}

void Templater::setFilter(const QString &filter)
{
    m_filter = filter;
}

PathList Templater::pathList() const
{
    return m_pathList;
}

void Templater::setPathList(const PathList &pathList)
{
    m_pathList = pathList;
}

void Templater::save()
{
    QDomDocument doc("tm");
    QDomElement root = doc.createElement("Template");
    doc.appendChild(root);

    QDomElement filterElement = doc.createElement("filter");
    QDomText filterTextNode = doc.createTextNode(m_filter);
    filterElement.appendChild(filterTextNode);
    root.appendChild(filterElement);

    QDomElement pathList = doc.createElement("pathList");
    root.appendChild(pathList);

    foreach (PathInfo pathInfo, m_pathList)
    {
        QDomElement pathElement = doc.createElement("path");
        pathElement.setAttribute("xpath", pathInfo.path);
        pathElement.setAttribute("key", pathInfo.key);
        pathList.appendChild(pathElement);
    }

    QFile file(m_fileName);
    if (!file.open(QIODevice::WriteOnly))
        return;
    QTextStream stream(&file);

    doc.save( stream, 4 );
    stream.flush();
}

void Templater::load()
{
    QFile file( m_fileName );
    if ( !file.exists() )
        return;

    if ( !file.open(QIODevice::ReadOnly) )
        return;

    // Загрузка XML
    QDomDocument doc;
    if ( !doc.setContent(&file) )
    {
        file.close();
        return;
    }

    file.close();

    QDomElement root = doc.documentElement();
    QDomElement filterEl = root.firstChildElement("filter");
    if ( filterEl.isNull() )
        return;

    m_filter = filterEl.text();

    m_pathList.clear();
    QDomElement pathList = root.firstChildElement("pathList");
    for(QDomElement pathEl = pathList.firstChildElement(); !pathEl.isNull(); pathEl = pathEl.nextSiblingElement())
    {
        QString path = pathEl.attribute("xpath");
        QString key = pathEl.attribute("key");

        PathInfo pi; pi.key = key; pi.path = path;
        m_pathList << pi;
    }
}
